package com.efounder.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.efounder.adapter.MallSelectionPayMultiAdapter;
import com.efounder.bean.MallSelectionPayMultipleBean;
import com.efounder.bean.MallTreasurePayOrderInfoBean;
import com.efounder.bean.UpdateOrderBadgeEvent;
import com.efounder.mobilemall.R;
import com.efounder.ospopenplanet.wxapi.WXPayEntryActivity;
import com.efounder.presenter.MallSelectionPayNoAliWxPresenter;
import com.efounder.util.ToastUtil;
import com.efounder.utils.Utils;
import com.pansoft.mobilemallpay.pays.AliPay;
import com.pansoft.mobilemallpay.pays.OnPayListener;
import com.pansoft.mobilemallpay.pays.PayInter;
import com.pansoft.openplanet.activity.AmountRechargeActivity;
import com.efounder.mvp.base.MvpBaseActivity;
import com.pansoft.openplanet.util.TCMathUtil;
import com.utilcode.util.ConvertUtils;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : zzj
 * e-mail : zhangzhijun@pansoft.com
 * date   : 2018/9/17 20:27
 * desc   : 夺宝 选择支付 activity
 * version: 1.0
 */
public class MallSelectionPayNoAliWxActivity extends MvpBaseActivity<MallSelectionPayNoAliWxPresenter> implements View.OnClickListener{


    /**
     * recyclerView
     */
    private RecyclerView rvSelectionPay;
    /**
     * 订单提醒文本
     */
    private TextView tvOrderHint;

    /**
     * 支付按钮
     */
    private Button btnPay;

    /**
     * 列表适配器
     */
    private MallSelectionPayMultiAdapter mallSelectionPayMultiAdapter;
    /**
     * 订单id，订单金额，订单title
     */
    private String orderAmount, goodsId;

    private ArrayList<String> orderIds;
    /**
     * 数据集合
     */
    private List<MallSelectionPayMultipleBean> selectionPayMultipleBeans = new ArrayList<>();
    /**
     * 订单详情的数据类
     */
    private MallTreasurePayOrderInfoBean orderDetail;

    @Override
    protected MallSelectionPayNoAliWxPresenter initPresenter() {
        return new MallSelectionPayNoAliWxPresenter(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.mall_activity_selection_pay;
    }

    public static void start(Context context, ArrayList<String> orderId,  String goodsId,String orderAmount) {
        Intent starter = new Intent(context, MallSelectionPayNoAliWxActivity.class);
        starter.putStringArrayListExtra("orderId", orderId);
        starter.putExtra("goodsId", goodsId);
        starter.putExtra("orderAmount", orderAmount);
        context.startActivity(starter);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        Bundle bundle = getIntent().getExtras();
        orderIds = bundle.getStringArrayList("orderId");
        orderAmount = bundle.getString("orderAmount");
        goodsId = bundle.getString("goodsId");
//        goodsId = "20181105";
        findViewById(R.id.title).setVisibility(View.VISIBLE);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.mall_selection_pay_title);
        tvOrderHint = (TextView) findViewById(R.id.tv_order_hint);
        btnPay = (Button) findViewById(R.id.btn_pay);
        tvOrderHint.setVisibility(View.INVISIBLE);
        btnPay.setOnClickListener(this);
        rvSelectionPay = (RecyclerView) findViewById(R.id.mall_rv_selection_pay);
        rvSelectionPay.setLayoutManager(new LinearLayoutManager(this));

        mallSelectionPayMultiAdapter = new MallSelectionPayMultiAdapter(selectionPayMultipleBeans);
        rvSelectionPay.setAdapter(mallSelectionPayMultiAdapter);
        initEvent();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (orderIds != null) {
            //请求订单详情
            presenter.getOrderDetailsData("", orderIds.get(0));
        }
    }

    @Override
    public void initEvent() {
        //adapter的点击事件
        mallSelectionPayMultiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                presenter.onAdapterItemClick(adapter, selectionPayMultipleBeans, position);
            }
        });
        //列表中按钮的点击事件
        mallSelectionPayMultiAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if(view.getId() == R.id.tv_go_recharge){
                    MallSelectionPayMultipleBean.SelectionPay selectionPay = selectionPayMultipleBeans.get(position).getSelectionPay();
                    AmountRechargeActivity.start(MallSelectionPayNoAliWxActivity.this,selectionPay.getTitle(),selectionPay.getTokenTypeId());
                }
            }
        });

    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        //支付按钮点击事件
        if (i == R.id.btn_pay) {

            MallSelectionPayMultipleBean selectionPayBean = null;
            //遍历当前选择的支付方式
            for (MallSelectionPayMultipleBean selectionPayMultipleBean : selectionPayMultipleBeans) {
                if (selectionPayMultipleBean.getSelectionPay().isSelectPayWay()) {
                    selectionPayBean = selectionPayMultipleBean;
                }
            }
            //当前是否选择了支付方式
            if (selectionPayBean != null) {
                if (orderDetail != null) {
                    //判断当前支付是现金支付还是积分支付
                    if(selectionPayBean.getItemType() == MallSelectionPayMultipleBean.PAY_WAY_ITEM){
                        //积分支付  积分支付传抵扣积分
                        if(selectionPayBean.getSelectionPay().getSurplusNum().equals("")){
                            ToastUtils.showShort(getString(R.string.mall_selection_pay_get_integral_fail));
                            return;
                        }
                        //矿工费
                         String gasPrice1 = "0.0004";
                        presenter.pay(orderIds.get(0),orderDetail.getSnatchGoodInfo().getId()+""
                                ,orderDetail.getSnatchGoodInfo().getOneChanceAddress(),
                                gasPrice1, TCMathUtil.retainAsignDecimalsWithZero(Double.valueOf(
                                        selectionPayBean.getSelectionPay().getTokenAmount()),2)
                                ,orderDetail.getOrder().getItems().get(0).getGoodNum()+"");
                    }

                }else {
                    ToastUtils.showShort(getString(R.string.mall_selection_pay_order_hint));
                }

            } else {
                ToastUtils.showShort(getString(R.string.mall_selection_pay_select_hint));
            }
        }
    }









    /**
     * 获取订单信息成功
     *
     * @param orderDetail 订单详情数据
     */

    public void getDataSuccess(MallTreasurePayOrderInfoBean orderDetail, List<MallSelectionPayMultipleBean> mallSelectionPayMultipleBeans) {
        if (orderDetail != null) {
            this.orderDetail = orderDetail;
            //虚拟币单位
            String priceUnit = orderDetail.getOrder()
                    .getItems().get(0).getGood().getMallGoodPrice().getPriceUnit();

            selectionPayMultipleBeans.clear();
            selectionPayMultipleBeans.addAll(mallSelectionPayMultipleBeans);
            orderAmount = TCMathUtil.retainAsignDecimalsWithZero(orderDetail.getOrder().getTotalPrice(), 2);

            String text = String.format(getString(R.string.mall_selection_pay_order_hint4)
                    ,priceUnit+orderAmount);
            tvOrderHint.setText(Utils.matcherSearchTextSize(getResources().getColor(R.color.op_orange_color)
                    , ConvertUtils.dp2px(16), text, new String[]{orderAmount}));
            tvOrderHint.setVisibility(View.VISIBLE);
            tvOrderHint.setPadding(0,ConvertUtils.dp2px(20),0,ConvertUtils.dp2px(20));
            presenter.loadBalanceData(selectionPayMultipleBeans,0,"",priceUnit,mallSelectionPayMultiAdapter);
//            mallSelectionPayMultiAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 支付成功
     *
     * @param finalPay 支付
     */

    public void paySuccess(PayInter finalPay) {
        //如果是订单列表了付款，需要通知订单角标刷新
        EventBus.getDefault().post(new UpdateOrderBadgeEvent());
        Intent intent = new Intent(activity, MallGeneralOrderActivity.class);
        intent.putExtra("targetIndex", 0);
        startActivity(intent);
        finish();
    }

    /**
     * 支付失败
     *
     * @param finalPay 支付方式
     * @param msg      失败信息
     * @param code     失败code
     */

    public void payFailed(PayInter finalPay, String msg, int code) {
        if (code == OnPayListener.ERROR) {
            ToastUtil.showToast(MallSelectionPayNoAliWxActivity.this, msg);
            if (finalPay instanceof AliPay) {
                //阿里支付成功后需要手动跳转到支付成功界面
                //微信会自动跳转到成功界面;
                Intent intent = new Intent(MallSelectionPayNoAliWxActivity.this, WXPayEntryActivity.class);
                intent.putExtra("type", "ali");
                intent.putExtra("status", "failure");
                startActivity(intent);
            } else if (finalPay == null) {
                Intent intent = new Intent(MallSelectionPayNoAliWxActivity.this, WXPayEntryActivity.class);
                intent.putExtra("type", "ali");
                intent.putExtra("status", "failure");
                startActivity(intent);
            }
        }
    }




    @Override
    protected void onDestroy() {
        super.onDestroy();


    }
}
